<template>
  <BasicModal
    :title="getTitle"
    :width="400"
    :canFullscreen="false"
    :centered="true"
    :destroyOnClose="true"
    @register="registerModal"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" :model="modelRef"/>
  </BasicModal>
</template>

<script lang="ts" name="BankModal" setup>
import { ref, computed, unref, reactive } from "vue";
import { BasicModal, useModalInner } from "/@/components/Modal";
import { BasicForm, useForm } from "/@/components/Form/index";
import { useMessage } from "/@/hooks/web/useMessage";
import { list, queryById, save } from "/@/views/weixin/menu/menu.api";
import { autoCompleteProps } from "ant-design-vue/es/auto-complete";
import { UploadTypeEnum } from '/@/components/Form/src/jeecg/components/JUpload';

const $message = useMessage();

// 声明Emits
const emit = defineEmits(['success', 'register']);

//表单modal
const modelRef = ref();
const isUpdate = ref(true);

//表单配置
const [registerForm, {resetFields, setFieldsValue, updateSchema, validate, clearValidate}] = useForm({
  schemas: [
    { label: "", field: "id", component: "Input", show: false },
    { label: "菜单名称", field: "name", component: "Input", required: true,
      componentProps: {
        autoComplete: "off",
      },
     },
    { label: "上级菜单", field: "fatherid", component: 'TreeSelect', required: false,
      componentProps: {
        fieldNames: {
          label: 'name',
          key: 'id',
          value: 'id'
        },
        dropdownStyle: {
          maxHeight: '50vh',
        },
        getPopupContainer: () => document.body,
      },
    },
    { label: "动作设置", field: "type", required: true, component: 'Select',
      defaultValue: 'click',
      componentProps: ({ formActionType }) => {
        return {
          options: [
            { label: '消息触发类', value: 'click' },
            { label: '网页链接类', value: 'view' },
          ],
          onChange: (value) => {
            const { updateSchema, clearValidate } = formActionType;
            //清除校验
            clearValidate();
            // if (value == 'click') {
            //   updateSchema([
            //     { field: "url", required: false, show: false },
            //     { field: "msgtype", required: true, show: true },
            //   ]);
            // } else {
            //   updateSchema([
            //     { field: 'url', required: true, show: true } ,
            //     { field: "msgtype", required: false, show: false },
            //   ]);
            // }
          },
        };
      },
    },
    {
      label: "URL",
      field: "url",
      component: "Input",
      required: true,
      componentProps: { placeholder: "填写url，格式需要以http开头" },
      ifShow: ({ values }) => { return (values.type == 'view'); },
    },
    { label: "消息类型", field: "msgtype", component: "RadioGroup", required: true,
      componentProps: ({ formActionType }) => {
        return {
          options: [
            { label: '文本', value: 'text' },
            { label: '图文', value: 'news' },
            { label: '扩展', value: 'expand' },
          ],
        }
      },
      ifShow: ({ values }) => { return (values.type == 'click'); },
    },
    {
      label: '图片',
      field: 'pictureUrl',
      component: 'JUpload',
      componentProps: {
        fileType: UploadTypeEnum.image,
        maxCount: 1,
        bizPath: 'menu'
      },
      colProps: { span: 21 },
      ifShow: ({ values }) => {
        return (!!values.fatherid);
      },
    },
    { label: "排序", field: "orders", component: "Input", componentProps: { placeholder: " " } }
  ],
  labelWidth: 90,
  baseColProps: {span: 22},
  showActionButtonGroup: false,
});


//表单赋值
const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
  await resetFields()
  setModalProps({confirmLoading: false});
  isUpdate.value = !!data?.isUpdate;
  modelRef.value = {};

  if (isUpdate.value) {
    //record = await queryById({id: data?.record?.id});
    Object.assign(modelRef, data.record);
  }

  //获取下拉树信息
  const treeData = await list();
  updateSchema([
    { field: 'fatherid', componentProps: { treeData } },
  ]);

  // 无论新增还是编辑，都可以设置表单值
  // console.info("data.record@@", data.record.cId)
  if (typeof data.record === "object") {
    await setFieldsValue({
      ...data.record
    });
  }

  await clearValidate();
});
//标题
const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

//表单提交事件
async function handleSubmit() {
  try {
    setModalProps({confirmLoading: true});
    const values = await validate();
    await save(values).then((res) => {
      if (res.success) {
        $message.createMessage.success(res.message);
        //关闭弹窗
        closeModal();
        emit("success")
      } else {
        $message.createMessage.warning(res.message);
      }
    });
  } catch (e) {
    console.log(e);
  } finally {
    setModalProps({confirmLoading: false});
  }
}

</script>

<style lang="less" scoped>

</style>
